from fastapi import FastAPI
from starlette_exporter import PrometheusMiddleware, handle_metrics
import os

class PrometheusService:
    """Prometheus监控工具类
    
    提供FastAPI应用集成Prometheus监控的工具方法
    """
    
    @staticmethod
    def setup_prometheus(app: FastAPI, app_name: str = None):
        """为FastAPI应用设置Prometheus监控
        
        Args:
            app: FastAPI应用实例
            app_name: 应用名称，将显示在Prometheus指标中
        """
        # 从环境变量或参数获取应用名称，默认使用osms
        prom_app_name = app_name or os.environ.get('PROMETHEUS_APP_NAME', 'osms')
        
        # 添加Prometheus中间件，支持更多配置选项
        prefix = os.environ.get('PROMETHEUS_PREFIX', 'http')
        app.add_middleware(
            PrometheusMiddleware, 
            app_name=prom_app_name,
            prefix=prefix,
            group_paths=True,  # 路径分组，避免生成过多指标
            buckets=[0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0]  # 响应时间桶
        )
        
        # 检查是否已存在metrics端点
        existing_paths = {route.path for route in app.routes}
        if "/metrics" not in existing_paths:
            app.add_route("/metrics", handle_metrics)

